package ui;

import java.awt.Color;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import utils.DateConverter;
import utils.UIColors;

import mainpackage.Category;
import mainpackage.DataManager;
import mainpackage.Todo;

public abstract class AbstractTodoPresenter {

	protected AbstractTodoWindow todoWindow;
	protected DataManager dataManager;

	public AbstractTodoPresenter(AbstractTodoWindow addTodoWindow) {
		this.todoWindow = addTodoWindow;
	}

	public void startDateEntered() {
		// TODO
	}

	public void endDateEntered() {
		// TODO
	}

	abstract public void saveButtonClicked();

	public void setDataManager(DataManager dataManager) {
		this.dataManager = dataManager;
		fillCategories();
	}

	private void fillCategories() {
		List<Category> categories = dataManager.getCategories();
		for (Category c : categories) {
			todoWindow.addToComboBox(c.getName());
		}
	}

	protected boolean validateTimeIsFree(String startDate, String endDate) {
		Date start = null;
		Date end = null;
		try {
			start = DateConverter.stringToDate(startDate);
			end = DateConverter.stringToDate(endDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dataManager.timeIsFree(start, end);
	}

	protected void dropFieldHighlights() {
		todoWindow.getStartField().setBackground(Color.WHITE);
		todoWindow.getEndField().setBackground(Color.WHITE);
		todoWindow.getTitleField().setBackground(Color.WHITE);
	}

	/**
	 * validates fields, highlights wrong ones and returns if all fields are
	 * valid
	 * 
	 * @return
	 */
	protected boolean revalidateFields() {
		dropFieldHighlights();
		
		String name = todoWindow.getTodoName();
		String startTime = todoWindow.getTodoStartTime();
		String endTime = todoWindow.getTodoEndTime();

		boolean successfullyValidated = true;
		
		if (name.isEmpty()) {
			todoWindow.getTitleField().setBackground(UIColors.fieldHighlightColor);
			successfullyValidated = false;
		}
		if (!DateConverter.validateDateFormat(startTime)) {
			todoWindow.getStartField().setBackground(UIColors.fieldHighlightColor);
			successfullyValidated = false;
		}
		if(!DateConverter.validateDateFormat(endTime)) {
			todoWindow.getEndField().setBackground(UIColors.fieldHighlightColor);
			successfullyValidated = false;
		}
		if(successfullyValidated) {
			try {
				if (!DateConverter.stringToDate(startTime).before(
						DateConverter.stringToDate(endTime))) {
					todoWindow.getStartField().setBackground(
							UIColors.fieldHighlightColor);
					todoWindow.getEndField().setBackground(
							UIColors.fieldHighlightColor);
					successfullyValidated = false;
				}
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}
		
		return successfullyValidated;
	}

}
